package com.xiebishe.mylibrary.common.glide.glide;

import androidx.annotation.NonNull;

import com.bumptech.glide.load.Options;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.ModelLoader;
import com.bumptech.glide.load.model.ModelLoaderFactory;
import com.bumptech.glide.load.model.MultiModelLoaderFactory;
import com.xiebishe.mylibrary.common.glide.ImageLoader;
import com.xiebishe.mylibrary.common.glide.OkHttpStreamFetcher;


import java.io.InputStream;

import okhttp3.OkHttpClient;


public class OkHttpUrlLoader implements ModelLoader<GlideUrl, InputStream> {
    private final okhttp3.Call.Factory client;

    public OkHttpUrlLoader(@NonNull okhttp3.Call.Factory client) {
        this.client = client;
    }

    public boolean handles(@NonNull GlideUrl url) {
        return true;
    }

    public LoadData<InputStream> buildLoadData(@NonNull GlideUrl model, int width, int height, @NonNull Options options) {
        if (((Boolean)options.get(GlideImageLoaderStrategy.NEED_CUTTING) || (Boolean)options.get(GlideImageLoaderStrategy.NEED_RESIZE)) && width != 0 && height != 0) {
            String url = model.toStringUrl();
            model = new GlideUrl(ImageLoader.parseImageUrl(url, width, height, (Boolean)options.get(GlideImageLoaderStrategy.NEED_CUTTING)));
        }

        return new LoadData(model, new OkHttpStreamFetcher(this.client, model));
    }

    public static class Factory implements ModelLoaderFactory<GlideUrl, InputStream> {
        private static volatile okhttp3.Call.Factory internalClient;
        private final okhttp3.Call.Factory client;

        private static okhttp3.Call.Factory getInternalClient() {
            if (internalClient == null) {
                Class var0 = Factory.class;
                synchronized(Factory.class) {
                    if (internalClient == null) {
                        internalClient = new OkHttpClient();
                    }
                }
            }

            return internalClient;
        }

        public Factory() {
            this(getInternalClient());
        }

        public Factory(@NonNull okhttp3.Call.Factory client) {
            this.client = client;
        }

        @NonNull
        public ModelLoader<GlideUrl, InputStream> build(MultiModelLoaderFactory multiFactory) {
            return new OkHttpUrlLoader(this.client);
        }

        public void teardown() {
        }
    }
}

